package com.dwin.h5.app.ui.fragments;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.AnimationDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.dwin.h5.app.H5Application;
import com.dwin.h5.app.R;
import com.dwin.h5.app.h5.X5WebView;
import com.dwin.h5.app.models.BaseJsonTool;
import com.dwin.h5.app.models.ResponseBean;
import com.dwin.h5.app.models.UserBean;
import com.dwin.h5.app.models.WeatherModel;
import com.dwin.h5.app.services.mqtt.DataSynEvent;
import com.dwin.h5.app.services.mqtt.MqttManager;
import com.dwin.h5.app.ui.MainActivity;
import com.dwin.h5.app.ui.pages.ConfigureNetAirKissActivity;
import com.dwin.h5.app.ui.pages.ScannerActivityV2;
import com.dwin.h5.app.ui.system.LoginActivity;
import com.dwin.h5.app.utils.Constants;
import com.dwin.h5.app.utils.DisplayUtil;
import com.dwin.h5.app.utils.MobileUtil;
import com.dwin.h5.app.utils.ToastUtil;
import com.dwin.h5.app.utils.http.OkHttpUtils;
import com.dwin.h5.app.utils.http.WeatherRetrofit;
import com.dwin.h5.app.views.dialogs.NetLoadingDialog;
import com.example.qrcode.Constant;
import com.example.qrcode.ScannerActivity;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import org.apache.commons.lang3.StringEscapeUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONObject;
import org.litepal.LitePal;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * H5显示的基类，处理h5的交互逻辑
 * 根据不同的url显示不同页面内容
 */
@Deprecated
public class BaseH5Fragment extends BaseFragment {
    private static final String TAG = "BaseH5Fragment";
    private static final int CODE_QRCODE = 999;
    public static final int CODE_CONFIG_NET = 1000;

    private View rootView;
    private String pageUrl; // h5页面的url地址
    private X5WebView mWebView;

    protected String auth = "";
    protected String qrCodeIdFlag;
    private RelativeLayout rl_loading; // webView 加载中，显示UI
    private RelativeLayout rl_loading_failed; // 加载失败，显示的view
    private boolean h5HasError = false; // h5页面异常，标识位

    //--------------------
    private static final int CODE_LOST = 100; // 网络丢失的code
    private boolean isNetLostFlag = false; // 网络切换，导致mqtt网络连接丢失。

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mContext = getActivity();
        return inflater.inflate(R.layout.fragment_base_h5, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);

        rl_loading = view.findViewById(R.id.rl_loading);
        rl_loading_failed = view.findViewById(R.id.rl_loading_failed);
        ImageView iv_loading = view.findViewById(R.id.iv_loading); // 加载中：页面动画添加
        iv_loading.setBackgroundResource(R.drawable.anim_loading_h5);
        AnimationDrawable ad = (AnimationDrawable) iv_loading.getBackground();
        ad.start();

        rootView = view;
        mWebView = view.findViewById(R.id.web_view);
        List<UserBean> list = LitePal.findAll(UserBean.class);
        if (list != null && list.size() > 0) {
            mUser = list.get(0); // 获取用户信息
            auth = mUser.auth;
        }

        if (pageUrl != null) {
            mWebView.loadUrl(pageUrl);
            rl_loading.setVisibility(View.VISIBLE);
            Log.d(TAG, "page  is : " + pageUrl);
            Log.d(TAG, "page progress is :0 ");
            mWebView.setOnWebViewListener(new X5WebView.OnWebViewListener() {
                @Override
                public void onProgressChanged(WebView webView, int progress) {
                    Log.d(TAG, "page progress is : " + progress);
                    if (progress == 100) {
                        rl_loading.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onReceiveTitle(String title) {
                    Log.d(TAG, "onReceiveTitle : " + title);
                }
            });
            mWebView.setWebViewClient(new WebViewClient() {
                @Override
                public void onReceivedError(WebView webView, int i, String s, String s1) {
                    super.onReceivedError(webView, i, s, s1);
                    rl_loading_failed.setVisibility(View.VISIBLE);
                    h5HasError = true;
                    Log.d(TAG, "onReceivedError 0000");
                }

                @Override
                public void onPageFinished(WebView webView, String s) {
                    super.onPageFinished(webView, s);
                    Log.d(TAG, "onPageFinished 0000");
                    if (!h5HasError) {
                        rl_loading_failed.setVisibility(View.GONE);
                        rl_loading.setVisibility(View.GONE);
                    }
                }
            });
        }
        rl_loading_failed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rl_loading.setVisibility(View.VISIBLE);
                rl_loading_failed.setVisibility(View.GONE);
                mWebView.reload(); // 刷新
            }
        });
    }

    // 重新
    public void reLoadPage() {
        if (pageUrl != null) {
            mWebView.loadUrl(pageUrl);
            rl_loading_failed.setVisibility(View.GONE);
            rl_loading.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                MqttManager.getInstance().release();
                if (mqttHandler != null) {
                    mqttHandler.removeMessages(CODE_LOST);
                }
            }
        }).start();
    }

    public void setPageUrl(String url) {
        this.pageUrl = url;
    }

    @Override
    public void onResume() {
        super.onResume();
        mWebView = rootView.findViewById(R.id.web_view);
        handler.postDelayed(runnable, TIME_SCAN);//每两秒执行一次runnable.
        Log.d(TAG, "page onResume ok ");
    }

    @Override
    public void onPause() {
        super.onPause();
        handler.removeCallbacks(runnable);
    }

    // 使用fragmentManager操作fragment的show和hide(注意：第一次创建fragment不会创建此方法)
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            handler.removeCallbacks(runnable);
//            Log.d(TAG, "onHiddenChanged 1 " + pageUrl);
        } else {
            handler.postDelayed(runnable, TIME_SCAN);//每两秒执行一次runnable.
//            Log.d(TAG, "onHiddenChanged 0 " + pageUrl);
        }
    }

    public static final int TIME_SCAN = 10; // 每间隔10ms轮询查消息
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(this, TIME_SCAN); // 从队列取mqtt消息
//            Log.d(TAG, "runnable getMessage： " + pageUrl);
            // 处理h5返回给app的消息队列数据
            if (H5Application.h5MessageTool.getReceiveMsgCount() > 0) {
                String msg = H5Application.h5MessageTool.getReceiveMsg();
                if (msg == null) {
                    return;
                }
                Log.d(TAG, msg);
                try {
                    JSONObject jsonObject = new JSONObject(msg);
                    String type = jsonObject.getString("type");
                    String command = jsonObject.getString("command");
                    String idflag = jsonObject.getString("idflag");
                    String isShowLoading = "1"; // 0不显示转圈圈，1显示转圈圈
                    if (jsonObject.has("isShowLoading")) {
                        isShowLoading = jsonObject.getString("isShowLoading");
                    }

                    if ("4".equals(type)) { // 网络类（http,https,mqtt）
                        if ("http".equals(command) || "https".equals(command)) {
                            JSONObject jsonData = jsonObject.getJSONObject("data");
                            String url = jsonData.getString("url");
                            String method = jsonData.getString("method");
                            JSONObject headers = jsonData.getJSONObject("param");
                            Iterator<String> headerkeys = headers.keys();
                            if ("get".equalsIgnoreCase(method)) {
                                Map<String, String> map = new HashMap<>();
                                while (headerkeys.hasNext()) {
                                    String key = headerkeys.next();
                                    map.put(key, headers.getString(key));
                                }
                                getHttp(url, idflag, isShowLoading, map); // http get 请求
                            } else if ("post".equalsIgnoreCase(method)) {
                                Map<String, Object> map = new HashMap<>();
                                JSONObject jsonParam = new JSONObject(jsonData.getString("param"));
                                Iterator<String> paramKeys = headers.keys();
                                while (paramKeys.hasNext()) {
                                    String key = paramKeys.next();
                                    Object value = jsonParam.get(key);
//                                    map.put(key, jsonParam.get(key));
                                    if (value instanceof String) {
                                        map.put(key, value);
                                    } else if (value instanceof JSONArray) { // 针对批量删除数据，处理
                                        JSONArray array = (JSONArray) value;
                                        List<String> ids = new ArrayList<>();
                                        for (int i = 0; i < array.length(); i++) {
                                            ids.add(array.getString(i));
                                        }
                                        map.put(key, ids);
                                    } else {
                                        map.put(key, jsonParam.get(key));
                                    }
                                }
                                String obj = new Gson().toJson(map);
                                RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), obj);
                                postHttp(url, idflag, isShowLoading, body);
                            }
                        }  // end of http/https
                        else if ("mqtt".equals(command)) {
                            // build message and send to h5 by appCallH5 interface
                            JSONObject jsonData = jsonObject.getJSONObject("data");
                            String info = jsonData.getString("info");
                            buildRAMReadMsg(info); // 发送mqtt消息
                        } // end of mqtt
                        else if ("mqttInfo2App".equals(command)) { // 得到mqtt的详细消息
                            JSONObject jsonData = jsonObject.getJSONObject("data");
                            JSONObject deviceDetail = jsonData.getJSONObject("deviceDetail");
                            String userTopic = deviceDetail.getString("user_topic");
                            String userSendTopic = deviceDetail.getString("user_send_topic");

                            JSONObject mqtt_info = deviceDetail.getJSONObject("mqtt_info");
                            String wxmqttserver = mqtt_info.getString("mqtt_server");
                            String wxmqttport = mqtt_info.getString("mqtt_port");
                            String mqttuser = mqtt_info.getString("mqtt_user");
                            String mqttpw = mqtt_info.getString("mqtt_pw");
                            buildMqttConnect(wxmqttserver, wxmqttport, mqttuser,
                                    mqttpw, userTopic, userSendTopic);
                        } // end of mqttInfo2App
                    } else if ("3".equals(type)) { // 音频类

                    } else if ("2".equals(type)) { // 硬件类
                        qrCodeIdFlag = idflag;
                        if ("gps".equals(command)) { // 获取位置信息
                            getAddrInfos();
                        } else if ("qrcode".equals(command)) {
                            callCamera();
                        } else if ("wifi".equals(command)) {
                            callConfigNet();
                        } else if ("setSaveData".equals(command)) { // 保存h5的数据
                            JSONObject jsonData = jsonObject.getJSONObject("data");
                            Iterator<String> it = jsonData.keys();
                            while (it.hasNext()) {
                                String key = it.next();
                                String value = jsonData.getString(key);
                                // Log.d(TAG, "save data key: " + key + ", value:" + value);
                                logMessage.edit().putString(key, value).commit();
                            }
                        } else if ("getSaveData".equals(command)) { // 读取保存的数据，返回给h5
                            JSONObject jsonData = jsonObject.getJSONObject("data");
                            Iterator<String> it = jsonData.keys();
                            ResponseBean responseBean = new ResponseBean();
                            responseBean.code = 0;
                            responseBean.message = "获取保存数据成功";
                            Map map = new HashMap();
                            while (it.hasNext()) {
                                String key = it.next();
                                String value = jsonData.getString(key); // 默认为空
                                // Log.d(TAG, "get data 00 key: " + key + ", value:" + value);
                                value = logMessage.getString(key, null); // get log data
                                // Log.d(TAG, "get data 01 key: " + key + ", value:" + value);
                                // JSONObject jsonObject1 = new JSONObject();
                                // jsonObject1.put(key, value);
                                map.put(key, StringEscapeUtils.escapeJson(value));
                            }
                            // 发送返回的数据给h5
                            responseBean.data = map;
                            appCallH5(mWebView, "", ACTION_HTTP, idflag, responseBean);
                        }
                    } else if ("1".equals(type)) { // 窗口类(隐藏tab)
                        if ("isShowMenu".equals(idflag)) { // 隐藏或显示，底部的Tab栏
                            ((MainActivity) getActivity()).setTabsVisiable(command);
                            if ("show".equals(command)) { // TODO 断开mqtt连接
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        MqttManager.getInstance().release();
                                        if (mqttHandler != null) {
                                            mqttHandler.removeMessages(CODE_LOST);
                                        }
                                    }
                                }).start();
                            }
                        }
                        // 选择了退出功能
                        if ("logout".equals(idflag) && "logout".equals(command)) {
                            // 退出逻辑，删除用户数据，回到登录页面
                            LitePal.deleteAll(UserBean.class); // 先删除所有用户数据
                            Intent intent = new Intent(mContext, LoginActivity.class);
                            intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TASK | intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }
                        // 主页面Tab切换动作  {"type":"1","command":"tab2","idflag":"switchHomeTab","data":{}}
                        if ("switchHomeTab".equals(idflag)) {
                            ((MainActivity) getActivity()).selectTab(command);
                        }
                    } else { // 默认值0或为空

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    // 子线程创建mqtt连接
    private void buildMqttConnect(final String wxmqttserver, final String wxmqttport, final String mqttuser,
                                  final String mqttpw, final String userTopic, final String userSendTopic) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String mqttUrl = "tcp://" + wxmqttserver + ":" + wxmqttport;
                String deviceUniId = MobileUtil.getUniqueId4Mqtt(mContext);
                try {
                    MqttManager.getInstance().disConnect();
                    MqttManager.release();
                } catch (MqttException e) {
                    e.printStackTrace();
                }
                Log.d(TAG, "userTopic:" + userTopic);
                Log.d(TAG, "userSendTopic:" + userSendTopic);
                List<String> userSendTopics = new ArrayList<>();
                userSendTopics.add(replaceLast(userSendTopic, "cli", "json"));
                userSendTopics.add(replaceLast(userSendTopic, "cli", "image"));
                boolean b = MqttManager.getInstance().creatConnect(mqttUrl, mqttuser, mqttpw,
                        replaceLast(userTopic, "cli", "json"),
                        listToArray(userSendTopics), deviceUniId);

                if (b) {
                    MqttManager.getInstance().subscribe(); // 订阅消息
                    ResponseBean responseBean = new ResponseBean();
                    responseBean.code = 0;
                    responseBean.message = "获取查询mqtt指令";
                    Map map = new HashMap();
                    responseBean.data = map;
                    appCallH5(mWebView, "", ACTION_MQTT, "mqttQuery", responseBean);
                    if (mqttHandler != null) {
                        mqttHandler.removeMessages(CODE_LOST);
                    }
                    Log.d(TAG, "mqtt update UI 建立连接成功：" + b);
                } else {
                    Log.d(TAG, "mqtt update UI 建立连接失败：" + b);
                    isNetLostFlag = true;
                }
            }
        }).start();
    }


    @Subscribe
    public void onEvent(DataSynEvent message) {
        String desc = message.getDetail();
        Log.d(TAG, "1022网络丢失啦------> " + desc);
        // mqtt网络丢失，释放资源，重新建立连接
        isNetLostFlag = true;
        if (mqttHandler != null) {
            mqttHandler.removeMessages(CODE_LOST);
            mqttHandler.sendEmptyMessageDelayed(CODE_LOST, 10 * 1000);
        }
    }

    //  通过EventBus，获取收到的mqtt消息
    @Subscribe
    public void onEvent(MqttMessage message) {
        String payLoad = new String(message.getPayload());
        Log.d(TAG, "onEvent mqtt Msg: " + payLoad);
        ResponseBean responseBean = new ResponseBean();
        responseBean.code = 0;
        responseBean.message = "收到mqtt";
        Type type = new TypeToken<JsonObject>() {
        }.getType();
        JsonObject object = new Gson().fromJson(payLoad, type);
        responseBean.data = object;
        appCallH5(mWebView, "", ACTION_MQTT, "getMqttInfo", responseBean);
    }


    Handler mqttHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            reConnectMqtt(); // MQTT 网络重连
        }
    };

    private void reConnectMqtt() {
        if (isNetLostFlag) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean b = MqttManager.reConnect();
                    if (b) {
                        MqttManager.getInstance().subscribe(); // 订阅消息
                        if (mqttHandler != null) {
                            mqttHandler.removeMessages(CODE_LOST);
                        }
                        Log.d(TAG, "mqtt reCon 建立连接成功：" + b);
                    } else {
                        if (mqttHandler != null) {
                            mqttHandler.removeMessages(CODE_LOST);
                            mqttHandler.sendEmptyMessageDelayed(CODE_LOST, 10 * 1000);
                        }
                    }
                }
            }).start();
        }
    }

    public Map buildQueryMapInfo() {
        Map map = new HashMap();
        map.put("speed", 0);
        map.put("pattern", 0);
        return map;
    }
    // end of mqtt

    // HTTP Post 请求
    protected void postHttp(final String url, final String idFlag, final String isShowLoading, RequestBody body) {
        if (!isNetworkConnected(mContext)) {
            ToastUtil.toastShort(mContext, R.string.net_error);
            return;
        }
        if ("1".equals(isShowLoading)) {
            NetLoadingDialog.showprogress(mContext, false);
        }
        language = logMessage.getString("language", "zh");
        OkHttpUtils.getInstance().post(auth, language, url, body, new OkHttpUtils.RealCallback() {
            @Override
            public void onResponse(Call call, Response response) {
                try {
                    String responseData = response.body().string();
                    Type type = new TypeToken<ResponseBean>() {
                    }.getType();
                    ResponseBean bean = new Gson().fromJson(responseData, type);
                    String msg = bean.message;
//                    Log.d(TAG, "postHttp result: " + responseData);
                    logDebug(TAG + " postHttp result:", responseData);
                    JSONObject jsonObject = new JSONObject(responseData);
                    int code = bean.code;
                    if (response.isSuccessful() && code == Constants.HTTP_OK) {
                        appCallH5(mWebView, "", ACTION_HTTP, idFlag, bean);
                    } else {
                        appCallH5(mWebView, "", ACTION_HTTP, idFlag, bean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                NetLoadingDialog.dismissprogress();
            }

            @Override
            public void onFailure(Call call, IOException e) {
                NetLoadingDialog.dismissprogress();
            }
        });
    }

    // get请求
    protected void getHttp(String url, final String idFlag, final String isShowLoading, Map<String, String> map) {
        if (!isNetworkConnected(mContext)) {
            ToastUtil.toastShort(mContext, R.string.net_error);
            return;
        }
        if ("1".equals(isShowLoading)) {
            NetLoadingDialog.showprogress(mContext, false);
        }
        language = logMessage.getString("language", "zh");

        OkHttpUtils.getInstance().get(auth, language, url, map, new OkHttpUtils.RealCallback() {
            @Override
            public void onResponse(Call call, Response response) {
                try {
                    String responseData = response.body().string();
//                    Log.d(TAG, "getHttp result: " + responseData);
                    logDebug(TAG + " getHttp result:", responseData);
                    Type type = new TypeToken<ResponseBean>() {
                    }.getType();
                    final ResponseBean bean = new Gson().fromJson(responseData, type);
                    String msg = bean.message;
                    appCallH5(mWebView, "", ACTION_HTTP, idFlag, bean);
//                    new Handler().postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            appCallH5(mWebView, "", ACTION_HTTP, idFlag, bean);
//                        }
//                    }, 500);

                    if (response.isSuccessful() && bean.code == Constants.HTTP_OK) {
                    } else {
                        ToastUtil.toastShort(mContext, msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                NetLoadingDialog.dismissprogress();
            }

            @Override
            public void onFailure(Call call, IOException e) {
                NetLoadingDialog.dismissprogress();
            }
        });
    }


    protected void appCallH5(final X5WebView webView, String method, String action, String idFlag, Object object) {
        this.mWebView = webView;
        final Map<String, Object> map = new HashMap<>();
        map.put("idflag", idFlag);
        map.put("data", object);
        final String json = new Gson().toJson(map);
        logDebug(TAG + " appCallH5 json:", json);
//        H5Application.h5MessageTool.addSendMsg(jsonObject.toString()); //  发送消息到发送队列中
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                webView.evaluateJavascript("javascript:appCallH5('" + json + "')", new ValueCallback<String>() { // TODO ok
                    //   webView.evaluateJavascript("javascript:appCallH5('999')", new ValueCallback<String>() { //  ok
                    @Override
                    public void onReceiveValue(String s) {
                        Log.d(TAG, "onReceiveValue: " + s);
                    }
                });
            }
        });
    }

    // 已获得地址信息, 请求更新天气信息
    public void getAddrInfos() {
        if (H5Application.addressComponent != null
                && H5Application.addressComponent.city != null
                && getActivity() != null
                && !getActivity().isDestroyed()) {
            String city = H5Application.addressComponent.city;
            if (city != null) { // 获取城市正常
                ResponseBean responseBean = new ResponseBean();
                responseBean.code = 0;
                responseBean.message = "获取城市名称完成";
                Map map = new HashMap();
                map.put("city", H5Application.addressComponent.city);
                map.put("district", H5Application.addressComponent.district);
                map.put("province", H5Application.addressComponent.province);
                map.put("street", H5Application.addressComponent.street);
                map.put("street_number", H5Application.addressComponent.street_number);
                map.put("direction", H5Application.addressComponent.direction);
                responseBean.data = map;
                appCallH5(mWebView, "", ACTION_HTTP, "getCity", responseBean);
            }
        } else {
            // 未定位成功，请求定位权限并定位
            if (hasPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
                doCoarseLocation();
            } else {
                requestPermissions(Constants.COARSE_LOCATION_CODE,
                        android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION);
            }
        }
    }

    LocationManager locationManager;
    TestLocationListener locationListener = new TestLocationListener();

    @Override
    public void doCoarseLocation() {
        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
        }
    }

    // 定位获取经纬度，监听
    private class TestLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            String msg = "onLocationChanged:latitude-> " + location.getLatitude() + " Longtitude-> " + location.getLongitude();
            // 位置发生改变时，调用这个方法
            getCityInfo(location.getLatitude(), location.getLongitude());
            locationManager.removeUpdates(locationListener);
        }

        @Override
        public void onProviderDisabled(String arg0) {
        }

        @Override
        public void onProviderEnabled(String arg0) {
        }

        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        }
    }

    // 根据经纬度，调用百度API，获取城市名称等信息， 并反馈给H5页面。
    private void getCityInfo(final double lat, final double Lng) {
        WeatherRetrofit.getInstance().getLocInfo(lat + "," + Lng, new retrofit2.Callback<WeatherModel>() {
            @Override
            public void onResponse(retrofit2.Call<WeatherModel> call, retrofit2.Response<WeatherModel> response) {
                if ("OK".equals(response.body().status)) {
                    // 验证码发送完成
                    H5Application.addressComponent = response.body().result.addressComponent;
                    H5Application.lat = lat;
                    H5Application.lng = Lng;
                    // 将位置信息反馈给h5
                    if (H5Application.addressComponent != null
                            && H5Application.addressComponent.city != null
                            && getActivity() != null
                            && !getActivity().isDestroyed()) {
                        String city = H5Application.addressComponent.city;
                        if (city != null) { // 获取城市正常
                            ResponseBean responseBean = new ResponseBean();
                            responseBean.code = 0;
                            responseBean.message = "获取城市名称完成";
                            Map map = new HashMap();
                            map.put("city", H5Application.addressComponent.city);
                            map.put("district", H5Application.addressComponent.district);
                            map.put("province", H5Application.addressComponent.province);
                            map.put("street", H5Application.addressComponent.street);
                            map.put("street_number", H5Application.addressComponent.street_number);
                            map.put("direction", H5Application.addressComponent.direction);
                            responseBean.data = map;
                            appCallH5(mWebView, "", ACTION_HTTP, "getCity", responseBean);
                        }
                    }
                }
            }

            @Override
            public void onFailure(retrofit2.Call<WeatherModel> call, Throwable t) {
                Log.d(TAG, "onFailure: ");
            }
        });
    }


    // 配网页面
    protected void callConfigNet() {
//        Intent intent = new Intent(mContext, ConfigureNetActivity.class);
        Intent intent = new Intent(mContext, ConfigureNetAirKissActivity.class);
        startActivityForResult(intent, CODE_CONFIG_NET);
    }

    // 调用相机，扫描二维码
    protected void callCamera() {
        if (hasPermission(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            doCameraPermission();
        } else {
            requestPermissions(Constants.CAMERA_CODE, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
    }

    @Override
    public void doCameraPermission() {
        Intent intent = new Intent(mContext, ScannerActivityV2.class);
        // 设置扫码框的宽
        intent.putExtra(Constant.EXTRA_SCANNER_FRAME_WIDTH, DisplayUtil.dip2px(mContext, 257));
        // 设置扫码框的高
        intent.putExtra(Constant.EXTRA_SCANNER_FRAME_HEIGHT, DisplayUtil.dip2px(mContext, 257));
        // 设置扫码框距顶部的位置
        intent.putExtra(Constant.EXTRA_SCANNER_FRAME_TOP_PADDING, DisplayUtil.dip2px(mContext, 136));
        // 可以从相册获取
        intent.putExtra(Constant.EXTRA_IS_ENABLE_SCAN_FROM_PIC, true);
        startActivityForResult(intent, CODE_QRCODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_QRCODE && resultCode == Activity.RESULT_OK) { // 二维码扫描结果
            if (data == null) {
                return;
            }
            String result = data.getExtras().getString(Constant.EXTRA_RESULT_CONTENT);
            // ToastUtil.toastLong(mContext, result); // 扫码成功后，回toast弹框提示。
            ResponseBean responseBean = new ResponseBean();
            responseBean.code = 0;
            responseBean.message = "扫码成功";
            Map map = new HashMap();
            map.put("qrcode", result);
            responseBean.data = map;
            appCallH5(mWebView, "", ACTION_HTTP, qrCodeIdFlag, responseBean);
        } else if (requestCode == CODE_CONFIG_NET && resultCode == Activity.RESULT_OK) {
            // 配网成功了，保存位置信息
            String device_bssid = data.getExtras().getString("device_bssid");
            ResponseBean responseBean = new ResponseBean();
            responseBean.code = 0;
            responseBean.message = "设备配网成功";
            Map map = new HashMap();
            map.put("device_bssid", device_bssid);
            map.put("gps_lat", H5Application.lat);
            map.put("gps_lng", H5Application.lng);
            map.put("gps_nation", H5Application.nation);
            map.put("gps_province", H5Application.addressComponent.province);

            map.put("gps_city", H5Application.addressComponent.city);
            map.put("gps_district", H5Application.addressComponent.district);
            map.put("gps_street", H5Application.addressComponent.street);
            map.put("gps_street_number", H5Application.addressComponent.street_number);
            responseBean.data = map;
            appCallH5(mWebView, "", ACTION_HTTP, "deviceSaveAddress", responseBean);
        }
    }

    private void buildRAMReadMsg(Map<String, Object> map) {
        map.put("__command_type", "READ");
        final String message = new JSONObject(map).toString();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "send query hex value: " + message);
                MqttManager.getInstance().publish(message.getBytes());
            }
        }).start();
    }

    private void buildRAMReadMsg(final String message) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "send query hex value: " + message);
                MqttManager.getInstance().publish(message.getBytes());
            }
        }).start();
    }

    private void buildSendMqttMsg(String type, Map<String, Object> map) {
        map.put(BaseJsonTool.type_CMD, type);
        final String message = new JSONObject(map).toString();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "send hex value: " + message);
                MqttManager.getInstance().publish(message.getBytes());
            }
        }).start();
    }

    public boolean webViewGoBack() {
        if (mWebView != null && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return false;
    }

}
